package com.udata.client.user;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.udata.client.service.UserService;
import com.udata.client.service.UserServiceAsync;
import com.udata.client.stoke.StokeWidget;
import com.udata.shared.model.UserB;

public class LoginWidget extends Composite {

	private UserServiceAsync userService = GWT.create(UserService.class);

	private StokeWidget stockWidget = new StokeWidget();
	private RegisterWidget registerWidget = new RegisterWidget();

	interface MyUiBinder extends UiBinder<HTMLPanel, LoginWidget> {
	}

	public LoginWidget() {

		initWidget(uiBinder.createAndBindUi(this).asWidget());
	}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	@UiField
	TextBox id;

	@UiField
	TextBox password;

	@UiField
	Button login;

	@UiField
	Button register;

	@UiHandler("login")
	void handleClick(ClickEvent e) {

		userService.getUser(id.getText(), password.getText(),
				new AsyncCallback<UserB>() {

					@Override
					public void onFailure(Throwable caught) {
						GWT.log(caught.getLocalizedMessage());
						Window.alert("No access.");
					}

					@Override
					public void onSuccess(UserB result) {
						GWT.log("success");
						Cookies.setCookie("PSFE_user", result.getId() + ";"
								+ result.getName());
						GWT.log(Cookies.getCookieNames().toString());
						RootPanel.get().clear();
						RootPanel.get().add(stockWidget);
					}
				});
	}

	@UiHandler("register")
	void handleRegisterClick(ClickEvent e) {
		RootPanel.get().clear();
		RootPanel.get().add(registerWidget);
	}

}
